import { User } from '../models';


export async function getSuperAdmin(){
    
}

export async function isUsernameExist(username){
    const user = await User.findOne({where:{username}});
    
    if(user){
        return true
    }
    return false;
}
export async function isMobileExist(mobile){
    const user = await User.findOne({where:{mobile}});
    if(user){
        return true
    }
    return false;
}

export async function isEmailExist(email){
    const user = await User.findOne({where: {email}});
    if(user){
        return true
    }
    return false;
}


export async function registerNewUser(username, password, profile){
    const { mobile, email } = profile;
    if(await isUsernameExist(username)){
        return "username_is_exist"
    }
    if(await isMobileExist(mobile)){
        return "mobile_is_exist";
    }
    if(await isEmailExist(email)){
        return "email_is_exist";
    }
    const saltRounds = Math.random();
    const bcrypt  = require("bcrypt");
    const salt = bcrypt.genSaltSync(saltRounds);
    const hash = bcrypt.hashSync(password, salt);  
    const user = {
      username,
      password: hash,
      mobile,
      email,
      createdAt: new Date(),
      updatedAt: new Date()
    }
    try {
        return await User.create(user);
        
    } catch (error) {
        console.error(error);
        
    }
}


export async function registerManyNewUsers(users){
    
    for (let index = 0; index < users.length; index++) {
        const user = users[index];
        const { username, password, profile} = user;
        try {
            await registerNewUser(username, password, profile);

        } catch (error) {
            console.error(error);
            
        }
    }
}

export async function getUserByName(username){
    const user = await User.findOne({where: {
        username
    }})
    return user;
}